﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using YamrSyncDemo.DBSync;
using YamrSyncDemo.YammerData;
using YamrSyncDemo.YammerWrapper;
using YamrSyncLib.DBDataEnrichment;

namespace YamrSyncDemo
{
    class Program
    {
        /// <summary>
        /// Create a configuration file named "SensitiveData.config" and put it in the same place as "App.config". Add the 
        /// config.
        /// 
        /// The file should look like this:
        /// 
        /// <?xml version="1.0" encoding="utf-8" ?>
        /// <configuration>
        ///   <appSettings>
        ///     <add key="ClientID" value="Yammer Client ID" />
        ///     <add key="ClientSecret" value="Yammer Client Secret" />
        ///     <add key="UserName" value="User name used to log in to Yammer" />
        ///     <add key="Password" value="Password" />
        ///     <add key="CorpDomain" value="contoso.com" />
        ///    </appSettings>
        /// </configuration>
        /// 
        /// Or simply assign the values directly.
        /// </summary>
        /// <returns>Yammer connection configuration</returns>
        private static YammerConnectionConfig GetYammerConnectionConfig()
        {
            var result = new YammerConnectionConfig();
            using (AppConfig.Change("SensitiveData.config"))
            { 
                result.ClientID = ConfigurationManager.AppSettings["ClientID"];
                result.ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
                result.UserName = ConfigurationManager.AppSettings["UserName"];
                result.Password = ConfigurationManager.AppSettings["Password"];
                result.CorpDomain = ConfigurationManager.AppSettings["CorpDomain"];
            }
            return result;
        }

        /// <summary>
        /// Connects to Yammer using the given connection config, see GetYammerConnectionConfig() on how to provide the config.
        /// 
        /// Attention: A local MongoDB instance has to run on default port for this sample app to work. It will try to save the Yammer data to the database.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            try
            {
                var config = GetYammerConnectionConfig();

                var connection = new YammerConnection(config);
                if (connection.Connect())
                {
                    var yammer = new YammerWrap(connection);
                    var networks = yammer.GetAccessibleNetworks();

                    var networkName = config.CorpDomain;
                    var network = networks.FirstOrDefault(e => e.NetworkName.Equals(networkName, StringComparison.InvariantCultureIgnoreCase));
                    if (network == null)
                    {
                        throw new Exception("Cannot find network with name " + networkName);
                    }
                    connection.AccessToken = network.Token;

                    var db = new YammerDB(networkName);
                    var mongoDBRunning = db.Connect();
                    
                    if (mongoDBRunning) 
                        db.AddOrUpdateAccessibleNetworks(networks);

                    if (true)
                    {
                        // get messages from Yammer
                        var messages = yammer.ReadAllMessages();
                        foreach (var message in messages)
                        {
                            Console.WriteLine(message.MessageContent);
                            Debug.WriteLine(message.MessageContent);
                        }
                        // save to DB (MongoDB has to run!)
                        if (mongoDBRunning)
                            db.AddOrUpdateMessages(messages);
                    }

                    if (true)
                    {
                        // get groups from Yammer
                        var groups = yammer.GetAllGroups();
                        // save to DB (MongoDB has to run!)
                        if (mongoDBRunning)
                            db.AddOrUpdateGroups(groups);
                    }

                    if (false && mongoDBRunning)
                    {
                        // get group members - this ueses already retrieved groups from MongoDB
                        var groups = db.MongoDatabase.GetCollection<YammerGroup>("yammer.groups");
                        foreach (var group in groups.FindAll())
                        {
                            // get group members from Yammer
                            var groupMembers = yammer.GetGroupMembersIfPublic(group);
                            // save to DB (MongoDB has to run!)
                            db.AddOrUpdateGroupMembers(groupMembers);
                        }
                    }

                    if (false && mongoDBRunning)
                    {
                        // get messages with file attachments from Yammer - this uses already retrieved messages from MongoDB
                        var messagesWithFileAttachment = db.GetMessagesWithFileAttachments();
                        foreach (var msg in messagesWithFileAttachment)
                        {
                            yammer.GetAttachments(msg, (file, stream) =>
                                {
                                    // save to DB (MongoDB has to run!)
                                    db.SaveStream(stream, file.Path);
                                });
                        }
                    }

                    if (false)
                    {
                        // get users from Yammer
                        var users = yammer.GetAllUsers();
                        // save to DB (MongoDB has to run!)
                        if (mongoDBRunning)
                            db.AddOrUpdateUsers(users);
                    }

                    // data enrichment test
                    if (false && mongoDBRunning)
                    {
                        var enrich = new MessageEnrichment(db);
                        enrich.AddOrUpdateReplyCount();
                    }
                }

                // todo: close reponse object wResp !!
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred in Main:  " + ex.Message);
            }
        }
    }
}
